package com.ts.api.http.org.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.ts.api.http.org.entity.apply.OrgApplyLongYanQiNuoShangHai;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

import static com.gitee.apanlh.web.http.HttpContentType.APPLICATION_JSON;

/**
 * 安心分期-龙岩市企诺API全量15 上海
 *
 * @author 李源聪
 */
@ApiPlan(productId = "330", type = ApiPlanConvertType.ORG_PHONE_MD5)
public class ApiOrgPhoneMd5LongYanQiNuoShangHai implements ApiOrgPhoneMd5ConvertHandler {

    private static final String KEY = "1Xt7DfC0bFruQXK0yambZQ==";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        apiDataExchangeParameter.setHttpContentType(APPLICATION_JSON);
        return JsonUtils.toJson(MapUtils.newHashMap(newMap -> {
            newMap.put("channel", "127.0.0.1");
            newMap.put("phoneMd5", apiDataExchangeParameter.getPhoneMd5());
        }));
    }

    @Override
    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        OrgApplyLongYanQiNuoShangHai orgApplyLongYanQiNuoShangHai = new OrgApplyLongYanQiNuoShangHai();
        orgApplyLongYanQiNuoShangHai.setName(apiApplyParameter.getUserName());
        orgApplyLongYanQiNuoShangHai.setPhone(apiApplyParameter.getPhone());
        orgApplyLongYanQiNuoShangHai.setFolderId("2");
        orgApplyLongYanQiNuoShangHai.setSource("融客通");
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        orgApplyLongYanQiNuoShangHai.setOtherInformation(apiFieldConverter.getExtendInfo());
        SecretKey secretKey = AESKeyUtil.decodeKey(KEY);
        String encrypt = AESEncryptionUtil.encrypt(JsonUtils.toJson(orgApplyLongYanQiNuoShangHai), secretKey);
        return JsonUtils.toJson(MapUtils.newHashMap(newMap -> newMap.put("encryptedThreeStr", encrypt)));
    }

    @Override
    public RespOrgPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        return RespOrgPhoneMd5Apply.ofSuc();
    }

    /**
     * AES 数据加密解密工具类（参考）
     * @ Author LIEFox
     * @ Date 2024/8/12 10:33
     **/
    public static class AESEncryptionUtil {
        /**
         * data 加密数据
         * secretKey 密钥
         */
        public static String encrypt(String data, SecretKey secretKey) throws Exception {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedData = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedData);
        }

        /**
         * encryptedData 解密数据
         * secretKey 密钥
         */
        public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            return new String(decryptedData);
        }
    }

    /**
     * AES秘钥工具类（参考）
     * @ Author LIEFox
     * @ Date 2024/8/12 10:32
     **/
    public static class AESKeyUtil {
        public static SecretKey decodeKey(String encodedKey) {
            byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
            return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        }
    }
}
